/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.mobiwebinc.compconn.client;

import com.mobiwebinc.compconn.client.processor.Processor;
import com.mobiwebinc.compconn.communication.IOHandler;
import com.mobiwebinc.compconn.configuration.ClientConfiguration;
import com.mobiwebinc.compconn.configuration.Constant;
import com.mobiwebinc.compconn.factory.ClientProcessorFactory;

/**
 *
 * @author suraj
 */
public class ClientHandler extends Thread {

    IOHandler io;
    Processor processor;
    Authenticator authenticator;
    ConfigGrabber configurationGrabber;
    ClientList clientList;
    private ClientConfiguration clientConfiguration;
    boolean started ;

    public ClientHandler(IOHandler io) {
        this.io = io;
        authenticator = new Authenticator(io);
        clientConfiguration = new ClientConfiguration(io.getRemoteHostName());
        configurationGrabber = new ConfigGrabber(io,clientConfiguration);
        clientList = ClientList.getInstance();
        started = false ;
    }

    @Override
    public void run() {
        if (authenticator.authenticate()) {
            processor = ClientProcessorFactory.getInstance().getProcessor(configurationGrabber, authenticator);
            clientList.updateClient(this);
            started = true;
            processor.process();
        }
        done();
    }

    private void done() {
        clientList.removeClient(this);
    }

    public void clean() {
        if(started && !authenticator.isWriteOnly() && (io.getLastCommunicated() + Constant.CLEAN_TIME_INTERVAL) < System.currentTimeMillis()) {
            io.disconnect();
//            System.out.println("Disconnecting");
        }
    }

    public void disconnect() {
        io.disconnect();
    }

    /**
     * @return the clientConfiguration
     */
    public ClientConfiguration getClientConfiguration() {
        return clientConfiguration;
    }

    /**
     * @param clientConfiguration the clientConfiguration to set
     */
    public void setClientConfiguration(ClientConfiguration clientConfiguration) {
        this.clientConfiguration = clientConfiguration;
    }
}
